package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author: 亚当
 * @date: 2022年07月08日 14:51
 * @package: com.atguigu.msmservice.controller
 * @Description: MsmController
 */
@Api("短信发送")
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信验证码
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //先从Redis中获取验证码，如果获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
            if (!StringUtils.isEmpty(code)){
                return R.ok();
        }
        //生成随机的值，传递给阿里云
        code = RandomUtil.getFourBitRandom();
        Map<String,Object> param = new HashMap<>();
        param.put("code",code);
        //调用service的短信发送方法
        //暂时注释掉，因为阿里云短信服务暂时不可用
        /*boolean isSend = msmService.send(param,phone);
        if (isSend){
            //发送成功，把验证码放到redis里面，同事设置过期时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error().message("短信发送失败！");
        }*/
        redisTemplate.opsForValue().set(phone,"1234",5, TimeUnit.MINUTES);
        return R.ok();

    }
}
